package com.holystone.orca.itsm.shiro;

import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ShiroPermissionFactory extends ShiroFilterFactoryBean {

    private DubboServiceCatalog dubboServiceCatalog;

    /**
     * 初始化设置过滤链
     */
    @Override
    public void setFilterChainDefinitions(String definitions) {
        Map<String,Set<String>> urlRoles = dubboServiceCatalog.getSystemServiceApi().selectRolePermission();

        Map<String,String> otherChains = new HashMap<>();
        for (Map.Entry<String,Set<String>> entry : urlRoles.entrySet()) {
            Set<String> roleCodes = entry.getValue();
            StringBuilder roleBuilder = new StringBuilder();
            for(String roleCode : roleCodes){
                roleBuilder.append(",");
                roleBuilder.append(roleCode);
            }
            if (roleBuilder.length()>0) {
                String rolesStr = roleBuilder.toString().substring(1);
                otherChains.put(entry.getKey(), "roleOrFilter["+rolesStr+"]"); //  /discover/newstag  authc,roles[user,admin]
            }
        }
        //加载配置默认的过滤链
        Ini ini = new Ini();
        ini.load(definitions);
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
        if (CollectionUtils.isEmpty(section)) {
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        }
        //加上数据库中过滤链
        section.putAll(otherChains);
        // authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问 user:rememberMe后可访问
        section.put("/**", "user,kickout");
        setFilterChainDefinitionMap(section);
    }


    public void setDubboServiceCatalog(DubboServiceCatalog dubboServiceCatalog) {
        this.dubboServiceCatalog = dubboServiceCatalog;
    }
}
